import { useEffect, useState } from 'react'
import { Button, Card, Col, Form, type FormProps, Input, message, Modal, Row, Select } from 'antd'
import { InboxOutlined, PlusOutlined } from '@ant-design/icons'

import { FormItemUpload, TFile } from '@/components/FormItemUpload'
import { getGlobalState } from '@/globalStore/globalStore'
import { IUserInfo } from '@/globalStore/userInfo'
import { fileValidate, formAutoTrimOnBlur } from '@/utils/utils'
import { apiGetWaybillAttachDetail, apiUploadWaybillAttach } from '../../apis'
import type { AttachListParam, AttachListResultParam } from '../../interface'
import { getFileTypeName, useUrlParams } from '../../utils'
import { List } from './List'
import { popupSlot } from './utils'

/** 接受文件类型 */
const accept = `${fileValidate.PDF_ACCEPT},${fileValidate.EXCEL_ACCEPT},${fileValidate.IMG_ACCEPT}`

/** 附件详情 */
export const AttachmentInfosDetail = () => {
  const { waybillNo } = useUrlParams()
  const userInfo = getGlobalState().userInfo as IUserInfo
  const [attachmentList, setAttachmentList] = useState<AttachListResultParam[]>()
  const autoHeight = (attachmentList?.length || 0) <= 5

  const getWaybillAttachDetail = async () => {
    return apiGetWaybillAttachDetail({ sourceId: waybillNo, type: 1 }).then(res => {
      setAttachmentList(res.attachListResultParams)
    })
  }

  useEffect(() => {
    getWaybillAttachDetail()
  }, [])

  return (
    <Card
      // loading={baseLoading}
      title="附件信息"
      extra={
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            const update = popupSlot.insert(
              <AddModal
                onSuccess={async attachInfo => {
                  return new Promise(resolve => {
                    Modal.confirm({
                      title: '确认要添加吗？',
                      onOk: async () => {
                        await apiUploadWaybillAttach({ userId: userInfo.id, attachListParams: [{ ...attachInfo }] })
                        message.success('添加成功')
                        resolve()
                        setAttachmentList([{ ...attachInfo }, ...(attachmentList || [])])
                        getWaybillAttachDetail()
                      },
                    })
                  })
                }}
                destroy={() => update(null)}
              />,
            )
          }}
        >
          添加
        </Button>
      }
    >
      <div style={{ height: autoHeight ? undefined : 330 }}>
        <List list={attachmentList || []} boxAutoHeight={autoHeight} />
        <popupSlot.Slot />
      </div>
    </Card>
  )
}

/** 新增附件modal 无编辑 */
function AddModal({
  onSuccess,
  destroy,
}: {
  onSuccess: (attachInfo: AttachListParam) => void | Promise<void>
  destroy: () => void
}) {
  const { waybillNo } = useUrlParams()
  const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
  const [form] = Form.useForm<AttachListParam & { $fileList: TFile[] }>()
  const formProps: FormProps<AttachListParam & { $fileList: TFile[] }> = {
    form,
    scrollToFirstError: { block: 'center', behavior: 'smooth' },
    layout: 'vertical',
    preserve: true,
    initialValues: {},
    onBlur: e => formAutoTrimOnBlur({ event: e, form }),
  }
  return (
    <Modal
      title="新增附件信息"
      width={900}
      open={open}
      onCancel={onHide}
      afterOpenChange={afterOpenChange}
      onOk={async () => {
        form.submit() // 触发 scrollToFirstError
        let values = await form.validateFields()
        values = form.getFieldsValue(true)
        if (!values) return
        const { comment, fileType, $fileList } = values
        const currentValues: AttachListParam = {
          fileType,
          comment,
          fileName: $fileList?.[0].fileName,
          fileUrl: $fileList?.[0].fileUrl,
          waybillNo,
        }
        await onSuccess?.(currentValues)
        onHide()
      }}
    >
      <Form {...formProps}>
        <Row gutter={32}>
          <Col span={24}>
            <Form.Item
              label=""
              name="$fileList"
              rules={[{ required: true, message: '请上传文件' }]}
              getValueProps={(v: TFile[]): { value: TFile[] } => ({
                value: v ? v?.map(v => ({ fileName: v?.fileName, fileUrl: v?.fileUrl, fileSize: v?.fileSize })) : [],
              })}
              getValueFromEvent={(list: TFile[]): TFile[] =>
                list?.map(v => ({ fileName: v?.fileName, fileUrl: v?.fileUrl, fileSize: v?.fileSize })) || []
              }
            >
              <FormItemUpload dragger max={20} multiple maxCount={1} accept={accept} reqData={{ moduleType: 2 }}>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">将文件拖拽到此处，或点击上传</p>
                <p className="ant-upload-hint">
                  支持扩展名：{accept} <br />
                  单个文件大小不超过20M
                </p>
              </FormItemUpload>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="文件类型" name="fileType" rules={[{ required: true, message: '请选择文件类型' }]}>
              <Select
                placeholder="请选择文件类型"
                options={getFileTypeName.valueList.map(v => ({
                  label: getFileTypeName(v),
                  value: v,
                }))}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="备注" name="notes">
              <Input.TextArea placeholder="请输入备注,最多100个字符" maxLength={100} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}
